import CloseOutlinedIcon from '@mui/icons-material/CloseOutlined';
import DoneOutlinedIcon from '@mui/icons-material/DoneOutlined';
import {
    Backdrop,
    Box,
    Button,
    CircularProgress,
    Collapse,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Paper,
    Stack,
    SxProps,
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableRow,
    Tooltip,
    Typography
} from '@mui/material';
import { Theme } from '@mui/system';
import React, { useCallback, useEffect, useState } from 'react';
import shallow from 'zustand/shallow';

import { Action, OrganizationData, Status } from '../../../api/organization/organization';
import { useInfiniteScroll } from '../../../hooks/infinitive-scroll';
import { useLoadPendingOrganisation } from '../../../hooks/pending-organisation';
import { usePendingOrganizationActionStore } from '../../../stores/pending-organization-action-store';
import { GFSButton } from '../button/gfs-button';
import { useStyles } from '../dialogs/UIs/styled-mui-dialog';
import GFSTable from './gfs-table';
import { IFilter } from './search-sort-paging-header';
import { useGetThemeStateStore } from '../../../stores/theme';

const useTableHeadTableCellStyles: SxProps<Theme> = {
    font: 'Rubik',
    fontWeight: 500,
    color: '#BCB6E9',
    fontSize: 13,
    whiteSpace: 'nowrap',
    wordWrap: 'normal'
};

const useTableRowTableCellStyles: SxProps<Theme> = {
    font: 'Rubik',
    fontWeight: 400,
    fontSize: 13,
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    maxWidth: 100,
};

const OrganizationTable = ({ filter, status }: { filter: IFilter; status: Status }) => {
    const [pageLoading, setPageLoading] = useState(true);
    const {mode,isLight,setMode,color1,bgColor,bgColor1,bgColor0,txtColor,txtColor3} = useGetThemeStateStore();
    // const { pageLoading, items, error, loading, hasNextPage, sentryRef, status } = props;
    const { loadingAction, openDialog, openActionDialog, currentItems, handleNewItems } =
        usePendingOrganizationActionStore(
            (state) => ({
                loadingAction: state.loading,
                openDialog: state.openDialog,
                openActionDialog: state.openActionDialog,
                currentItems: state.currentItems,
                handleNewItems: state.handleNewItems
            }),
            shallow
        );

    const { loading, items, hasNextPage, error, loadMore } = useLoadPendingOrganisation(
        status,
        filter
    );

    const [sentryRef] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 400px 0px'
    });

    useEffect(() => {
        const load = async () => {
            await loadMore();
            setPageLoading(false);
        };

        load().then();
    }, []);

    useEffect(() => {
        handleNewItems(items ? items : [], status);
    }, [items]);

    const getErrorMessage = useCallback(
        (error: { code: number; message: string }) => {
            return error.message;
        },
        [items]
    );

    return (
        <>
            {pageLoading ? (
                <Box
                    display="flex"
                    justifyContent="center"
                    alignItems="center"
                    minHeight={'50vh'}
                    sx={{ mt: '24px' }}
                >
                    <CircularProgress sx={{ color: '#ffffff' }} />
                </Box>
            ) : (
                <Box sx={{ mt: '24px' }}>
                    {!error ? (
                        <>
                            {currentItems?.length > 0 && (
                                <Paper
                                    elevation={0}
                                    variant="outlined"
                                    className="d-flex justify-content-center align-items-center flex-column"
                                    sx={{
                                        background: bgColor,
                                        borderRadius: '12px',
                                        p:'0 32px !important',
                                        border:'0 !important',
                                        // marginTop: 7
                                    }}
                                >
                                    <GFSTable 
                                        sx={{
                                            boxShadow:'none !important',
                                        }}
                                    >
                                        <Table
                                            sx={{ minWidth: 650,
                                                borderCollapse: 'separate',
                                                borderSpacing: '0 4px',}}
                                            aria-label="collapsible table"
                                        >
                                            <TableHead>
                                                <TableRow>
                                                    <TableCell
                                                        align="left"
                                                        className={'m-t1'}
                                                        sx={useTableHeadTableCellStyles}
                                                    >
                                                        Name
                                                    </TableCell>
                                                    <TableCell
                                                        align="center"
                                                        className={'m-t1'}
                                                        sx={useTableHeadTableCellStyles}
                                                    >
                                                        Email address
                                                    </TableCell>
                                                    <TableCell
                                                        align="center"
                                                        className={'m-t1'}
                                                        sx={useTableHeadTableCellStyles}
                                                    >
                                                        Wallet address
                                                    </TableCell>
                                                    <TableCell
                                                        align="center"
                                                        className={'m-t1'}
                                                        sx={useTableHeadTableCellStyles}
                                                    >
                                                        Mobile number
                                                    </TableCell>
                                                    <TableCell
                                                        align="center"
                                                        className={'m-t1'}
                                                        sx={useTableHeadTableCellStyles}
                                                    >
                                                        Company name
                                                    </TableCell>
                                                    <TableCell
                                                        align="center"
                                                        className={'m-t1'}
                                                        sx={useTableHeadTableCellStyles}
                                                    >
                                                        Requested Date
                                                    </TableCell>
                                                    {status === Status.Pending && (
                                                        <TableCell
                                                            align="center"
                                                            className={'m-t1'}
                                                            sx={useTableHeadTableCellStyles}
                                                        >
                                                            Action
                                                        </TableCell>
                                                    )}
                                                    {status === Status.Approved && (
                                                        <TableCell
                                                            align="center"
                                                            className={'m-t1'}
                                                            sx={useTableHeadTableCellStyles}
                                                        >
                                                            Approval Date
                                                        </TableCell>
                                                    )}
                                                    {status === Status.Denied && (
                                                        <TableCell
                                                            align="center"
                                                            className={'m-t1'}
                                                            sx={useTableHeadTableCellStyles}
                                                        >
                                                            Date Denied
                                                        </TableCell>
                                                    )}
                                                </TableRow>
                                            </TableHead>
                                            <TableBody>
                                                {(currentItems as OrganizationData[]).map((row) => (
                                                    <Row key={row.id} row={row} />
                                                ))}
                                            </TableBody>
                                        </Table>
                                    </GFSTable>
                                </Paper>
                            )}
                            {!loading && (!currentItems || !currentItems.length) && (
                                <Typography
                                    className="text-white mt-4"
                                    align="center"
                                    justifyContent={'center'}
                                    display={'flex'}
                                    minHeight={'50vh'}
                                    alignItems={'center'}
                                >
                                    No Organisation to attend to yet...
                                </Typography>
                            )}
                            {sentryRef && (loading || hasNextPage) && (
                                <Box
                                    display="flex"
                                    justifyContent="center"
                                    alignItems="center"
                                    minHeight={'50vh'}
                                    sx={{ pt: 4 }}
                                >
                                    <CircularProgress ref={sentryRef} sx={{ color: '#ffffff' }} />
                                </Box>
                            )}
                        </>
                    ) : error?.message ? (
                        <Typography className="mt-4" sx={{ color: 'var(--color-negative)' }}>
                            {getErrorMessage(error)}
                        </Typography>
                    ) : (
                        <Typography
                            className="text-white mt-4"
                            align="center"
                            justifyContent={'center'}
                            display={'flex'}
                            minHeight={'50vh'}
                            alignItems={'center'}
                        >
                            No Organisation to attend to yet...
                        </Typography>
                    )}
                </Box>
            )}
            {(loadingAction || openActionDialog || openDialog) && <BackDropResponse />}
        </>
    );
};

function Row(props: { row: OrganizationData }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const {mode,isLight,setMode,color1,bgColor,bgColor1,bgColor0,txtColor,txtColor3} = useGetThemeStateStore();
    const { setActionData } = usePendingOrganizationActionStore(
        (state) => ({ setActionData: state.setActionData }),
        shallow
    );
    const created_at = new Date(Number(row.created_at));
    const updated_at = new Date(Number(row.updated_at));

    return (
        <React.Fragment>
            <TableRow 
                key={open?row.id+Math.random():row.id+Math.random()+66}
                sx={{
                    '&:last-child th': {
                        border: 0,

                    },
                    '&:last-child td':{
                        border: 0,
                        // borderBottomRightRadius:(open)?"0px !important":"12px",
                    },
                    '& td:last-child':{
                        // background:'red !important',
                        borderBottomRightRadius:(open)?"0px !important":"12px",
                    },
                    background:bgColor1+" !important",
                    borderRadius:'0 !important',


                }}
                onClick={() => setOpen(!open)}
            >
                <TableCell align="left" 
                sx={
                    {...useTableRowTableCellStyles,
                        ...{
                        borderBottomLeftRadius:(open)?"0px !important":"12px",
                        }
                    }
                } 
                >
                    <Tooltip title={row.name} arrow >
                        <span className={'m-t2'} style={{color:txtColor}}>{row.name}</span>
                    </Tooltip>
                </TableCell>
                <TableCell align="center" sx={useTableRowTableCellStyles}>
                    <Tooltip title={row.email} arrow>
                        <span className={'m-t3'} style={{color:txtColor}}>{row.email}</span>
                    </Tooltip>
                </TableCell>
                <TableCell align="center" sx={useTableRowTableCellStyles}>
                    <Tooltip title={row.wallet_address} arrow>
                        <span className={'m-t3'} style={{color:txtColor}}>{row.wallet_address}</span>
                    </Tooltip>
                </TableCell>
                <TableCell align="center" sx={useTableRowTableCellStyles}>
                    <Tooltip title={row.mobile_number} arrow>
                        <span className={'m-t3'} style={{color:txtColor}}>{row.mobile_number}</span>
                    </Tooltip>
                </TableCell>
                <TableCell align="center" sx={useTableRowTableCellStyles}>
                    <Tooltip title={row.company_name||''} arrow>
                        <span className={'m-t3'} style={{color:txtColor}}>{row.company_name||''}</span>
                    </Tooltip>
                </TableCell>
                <TableCell align="center" sx={useTableRowTableCellStyles}>
                    <Tooltip title={created_at.toDateString()} arrow>
                        <span className={'m-t3'} style={{color:txtColor}}>{created_at.toDateString()}</span>
                    </Tooltip>
                </TableCell>
                 {[Status.Approved, Status.Denied].includes(row.status) && (
                    <TableCell align="center" sx={useTableRowTableCellStyles}>
                        <Tooltip title={updated_at.toDateString()} arrow>
                            <span className={'m-t3'} style={{color:txtColor}}>{updated_at.toDateString()}</span>
                        </Tooltip>
                    </TableCell>
                )}
                <TableCell align="center">
                    <Stack spacing={2} direction="row" justifyContent="center">
                        {row.status === 1 && (
                            <GFSButton
                                sx={{
                                    fontWeight: '500',
                                    fontSize: 'small',
                                    lineHeight: '25px',
                                    width: '100px',
                                    height: '30px',
                                    borderRadius: '0.2rem',
                                    '&:hover': {
                                        boxShadow: 'none !important'
                                    }
                                }}
                                startIcon={<DoneOutlinedIcon sx={{ color: '#FFFFFF' }} />}
                                onClick={() => {
                                    setActionData(Action.Approved, row.id, row.name);
                                }}
                            >
                                Approve
                            </GFSButton>
                        )}
                        {row.status === 1 && (
                            <Button
                                sx={{
                                    fontWeight: '500',
                                    fontSize: 'small',
                                    lineHeight: '25px',
                                    width: '100px',
                                    height: '30px',
                                    padding: '2px',
                                    '&:hover': {
                                        boxShadow: 'none !important'
                                    },
                                    background: '#1F1D37'
                                }}
                                startIcon={<CloseOutlinedIcon sx={{ color: 'error' }} />}
                                onClick={() => {
                                    setActionData(Action.Denied, row.id, row.name);
                                }}
                            >
                                Deny
                            </Button>
                        )}
                    </Stack>
                </TableCell> 
                {/* <TableCell align="left" 
                sx={
                    {...useTableRowTableCellStyles,
                        ...{
                        borderBottomRightRadius:(open)?"0px !important":"12px",
                        }
                    }
                } 
                ></TableCell> */}
            </TableRow>
            <TableRow sx={{background:'transparent !important'}}>
                <TableCell style={{ padding: 0, }} colSpan={8}>
                    <Collapse in={open} timeout="auto" unmountOnExit>
                        <Box sx={{ 
                            margin: '-4px 0 4px' ,background:bgColor1,p:'16px',
                            borderBottomLeftRadius:"12px",
                            borderBottomRightRadius:"12px",
                             }}>
                            <Box
                                gutterBottom
                                component="span"
                                sx={{ color: '#FFBB59', font: 'Rubik', fontWeight: 600 }}
                            >
                                Message:
                            </Box>
                            <Box
                                gutterBottom
                                component="span"
                                sx={{ color: '#BCB6E9', font: 'Rubik', fontWeight: 400,ml:'6px' }}
                            >
                                {row.message}
                            </Box>
                        </Box>
                    </Collapse>
                </TableCell>
            </TableRow>
        </React.Fragment>
    );
}

function BackDropResponse() {
    const style = useStyles();
    const {
        openActionDialog,
        closeActionDialog,
        openBackdrop,
        openDialog,
        loading,
        message,
        organisationId,
        organisationName,
        closeDialog,
        action,
        handleClick
    } = usePendingOrganizationActionStore(
        (state) => ({
            openBackdrop: state.openBackdrop,
            openDialog: state.openDialog,
            loading: state.loading,
            message: state.message,
            organisationId: state.organisationId,
            organisationName: state.organisationName,
            closeDialog: state.closeDialog,
            handleClick: state.handleClick,
            openActionDialog: state.openActionDialog,
            closeActionDialog: state.closeActionDialog,
            action: state.action
        }),
        shallow
    );

    if (loading) {
        return (
            <Backdrop
                sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
                open={openBackdrop}
            >
                <CircularProgress color="inherit" />
            </Backdrop>
        );
    } else if (openDialog) {
        return (
            <>
                <Dialog open={openDialog} maxWidth="sm" fullWidth>
                    <Box className={`${style.dialogBackground} ${style.center}`}>
                        <DialogTitle>
                            <Typography variant="h4" align="center" sx={{ mt: 2 }}>
                                {action === Action.Approved ? 'Approved' : 'Denied'}
                            </Typography>
                        </DialogTitle>
                    </Box>
                    <DialogContent className={`${style.dialogBackground} ${style.center}`}>
                        <Typography
                            variant="caption"
                            align="center"
                            sx={{ width: 400, fontWeight: 'normal' }}
                        >
                            {message}
                        </Typography>
                    </DialogContent>
                    <DialogActions
                        className={`${style.dialogBackground} ${style.center}`}
                        sx={{ px: 4, py: 2 }}
                    >
                        <Button
                            color="secondary"
                            variant="contained"
                            onClick={closeDialog}
                            sx={{ width: 100, mb: 2 }}
                        >
                            Close
                        </Button>
                    </DialogActions>
                </Dialog>
            </>
        );
    } else {
        return (
            <>
                <Dialog open={openActionDialog} maxWidth="sm" fullWidth>
                    <Box className={`${style.dialogBackground} ${style.center}`}>
                        <DialogTitle>
                            <Typography variant="h4" align="center" sx={{ mt: 2 }}>
                                {action === Action.Approved ? 'Approve' : 'Deny'}
                            </Typography>
                        </DialogTitle>
                    </Box>
                    <DialogContent className={`${style.dialogBackground} ${style.center}`}>
                        <Typography
                            variant="caption"
                            align="center"
                            sx={{ width: 400, fontWeight: 'normal' }}
                        >
                            {action === Action.Approved
                                ? `Are you sure you want to approve ${organisationName} with id ${organisationId} ?`
                                : `Are you sure you want to deny ${organisationName} with id ${organisationId} ?`}
                        </Typography>
                    </DialogContent>
                    <DialogActions
                        className={`${style.dialogBackground} ${style.center}`}
                        sx={{ px: 4, py: 2 }}
                    >
                        <Button
                            color="primary"
                            variant="contained"
                            onClick={() => {
                                handleClick(action, organisationId, organisationName);
                            }}
                            sx={{ width: 100, mb: 2 }}
                        >
                            Continue
                        </Button>
                        <Button
                            color="secondary"
                            variant="contained"
                            onClick={closeActionDialog}
                            sx={{ width: 100, mb: 2 }}
                        >
                            Close
                        </Button>
                    </DialogActions>
                </Dialog>
            </>
        );
    }
}

export default OrganizationTable;
